package com.yyt.database_demo.utils;

import com.yyt.database_demo.domain.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yeyangtao
 * @date 2020/4/30 16:10
 */
@Component
public class JdbcUtil {
    @Resource
    private JdbcTemplate jdbcTemplate;

    public void batchCreate(List<User> obj) {
        String sql = "INSERT INTO db_user(username,password,phone)VALUES (?,?,?);";
        List<Object[]> parameters = new ArrayList<>();
        Long t1 = System.currentTimeMillis();
        for (User user : obj) {
            parameters.add(new Object[]{
                    user.getUsername(), user.getPassword(), user.getPhone()
            });
        }
        Long t2 = System.currentTimeMillis();
        System.out.println("jdbc数据准备时间：" + (t2 - t1));
        jdbcTemplate.batchUpdate(sql, parameters);
    }

    public void batchUpdate(List<User> obj) {
        String sql = "update db_user set username=?,password=?,phone=? where id = ?;";
        List<Object[]> parameters = new ArrayList<>();
        Long t1 = System.currentTimeMillis();
        for (User user : obj) {
            parameters.add(new Object[]{
                    user.getUsername(), user.getPassword(), user.getPhone(), user.getId()
            });
        }
        Long t2 = System.currentTimeMillis();
        System.out.println("jdbc数据准备时间：" + (t2 - t1));
        jdbcTemplate.batchUpdate(sql, parameters);
    }

}
